package cn.ocars.playgame.pencilstudy.ui.components

import android.graphics.Path
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.ocars.playgame.pencilstudy.R
import cn.ocars.playgame.pencilstudy.ui.theme.BackgroundWhite
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonBlue
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonGreen
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonRed
import cn.ocars.playgame.pencilstudy.ui.theme.PrimaryBlue
import cn.ocars.playgame.pencilstudy.ui.theme.TextPrimary
import cn.ocars.playgame.pencilstudy.ui.theme.TextWhite

/**
 * 低延迟书写卡片演示组件
 */
@Composable
fun LowLatencyWritingCardDemo(
    onBackClick: () -> Unit,
    practiceType: String = "words", // "words", "strokes", "radicals"
    modifier: Modifier = Modifier
) {
    // 根据练习类型选择字符集
    val characterList = when (practiceType) {
        "strokes" -> listOf("横", "竖", "撇", "捺", "点", "钩", "折") // 笔画练习
        "radicals" -> listOf("人", "口", "日", "月", "木", "水", "火", "土") // 偏旁练习
        else -> listOf("1", "一", "人", "大") // 默认词语练习
    }
    
    // 根据练习类型设置标题
    val title = when (practiceType) {
        "strokes" -> "笔画练习"
        "radicals" -> "偏旁练习"
        else -> "低延迟书写测试"
    }
    
    var currentCharacterIndex by remember { mutableStateOf(0) }
    var showResult by remember { mutableStateOf(false) }
    var scoreResult by remember { mutableStateOf<WritingScoreEvaluator.ScoreResult?>(null) }
    

    
    Surface(
        modifier = modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 标题栏
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Button(
                    onClick = onBackClick,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = ButtonBlue,
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "返回",
                        fontSize = 16.sp
                    )
                }
                
                Spacer(modifier = Modifier.weight(1f))
                
                Text(
                    text = title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = TextPrimary
                )
                
                Spacer(modifier = Modifier.weight(1f))
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 根据练习类型设置说明文本
            val instructionText = when (practiceType) {
                "strokes" -> "使用压感笔在浅色笔画上描摹（低延迟模式）"
                "radicals" -> "使用压感笔在浅色偏旁上描摹（低延迟模式）"
                else -> "使用压感笔在浅色字符上描摹（低延迟模式）"
            }
            
            // 说明文本
            Text(
                text = instructionText,
                fontSize = 16.sp,
                color = TextPrimary,
                textAlign = TextAlign.Center
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 低延迟书写卡片
            Box(
                modifier = Modifier
                    .size(150.dp)
                    .border(2.dp, PrimaryBlue, RoundedCornerShape(12.dp))
                    .background(BackgroundWhite, RoundedCornerShape(12.dp))
            ) {
                // 目标字符（浅色背景）
                Text(
                    text = characterList[currentCharacterIndex],
                    fontSize = 80.sp,
                    fontWeight = FontWeight.Bold,
                    color = PrimaryBlue.copy(alpha = 0.2f),
                    textAlign = TextAlign.Center,
                    modifier = Modifier.align(Alignment.Center)
                )
                
                // 低延迟书写组件
                LowLatencyWritingCard(
                    character = characterList[currentCharacterIndex],
                    onWritingComplete = { result ->
                        scoreResult = result
                        showResult = true
                    },
                    modifier = Modifier.fillMaxSize(),
                    onClearClick = {
                        showResult = false
                        scoreResult = null
                    }
                )
                
                // 笔画进度提示
                Text(
                    text = "低延迟模式",
                    fontSize = 12.sp,
                    color = PrimaryBlue,
                    modifier = Modifier
                        .align(Alignment.TopStart)
                        .background(Color.White.copy(alpha = 0.7f))
                        .padding(4.dp)
                )
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 字符切换按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(
                    onClick = {
                        if (currentCharacterIndex > 0) {
                            currentCharacterIndex--
                            showResult = false
                            scoreResult = null
                        }
                    },
                    enabled = currentCharacterIndex > 0,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (currentCharacterIndex > 0) ButtonBlue else ButtonBlue.copy(alpha = 0.5f),
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "上一个",
                        fontSize = 16.sp
                    )
                }
                
                Button(
                    onClick = {
                        if (currentCharacterIndex < characterList.size - 1) {
                            currentCharacterIndex++
                            showResult = false
                            scoreResult = null
                        }
                    },
                    enabled = currentCharacterIndex < characterList.size - 1,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (currentCharacterIndex < characterList.size - 1) ButtonBlue else ButtonBlue.copy(alpha = 0.5f),
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "下一个",
                        fontSize = 16.sp
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 评分结果
            if (showResult) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.White.copy(alpha = 0.8f))
                        .padding(16.dp)
                ) {
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "书写完成！",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = TextPrimary
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        scoreResult?.let { result ->
                            Text(
                                text = "${result.totalScore.toInt()}分",
                                fontSize = 24.sp,
                                fontWeight = FontWeight.Bold,
                                color = when {
                                    result.totalScore >= 90 -> ButtonGreen
                                    result.totalScore >= 70 -> ButtonBlue
                                    else -> ButtonRed
                                }
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Text(
                                text = result.feedback,
                                fontSize = 12.sp,
                                color = TextPrimary.copy(alpha = 0.8f),
                                textAlign = TextAlign.Center
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Button(
                            onClick = {
                                showResult = false
                                scoreResult = null
                            },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = ButtonBlue,
                                contentColor = TextWhite
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Text(
                                text = "继续",
                                fontSize = 16.sp
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 技术说明
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "低延迟技术特性",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = TextPrimary
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 前端缓冲区渲染：跳过SurfaceFlinger排队\n" +
                          "• 动作预测：提前1帧插值预测点\n" +
                          "• OpenGL直接渲染：避免Canvas上传GPU\n" +
                          "• 三星S Pen优化：支持240Hz报点率",
                    fontSize = 14.sp,
                    color = TextPrimary.copy(alpha = 0.7f),
                    textAlign = TextAlign.Center
                )
            }
    }
}

}